package com.rxt.thermopro.app

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGattServerCallback
import android.bluetooth.le.AdvertiseData
import android.bluetooth.le.AdvertisingSet
import android.bluetooth.le.AdvertisingSetCallback
import android.bluetooth.le.AdvertisingSetParameters
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.res.Resources
import android.graphics.Typeface
import android.os.Build
import android.os.IBinder
import android.os.ParcelUuid
import android.util.DisplayMetrics
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import com.app.common.base.BaseApp
import com.github.mikephil.charting.charts.Chart.LOG_TAG
import com.orhanobut.hawk.Hawk
import com.rxt.ble.BleManager
import com.rxt.thermopro.ex.ActionSound
import java.util.*


class AppContext : BaseApp() {

    companion object {
        @SuppressLint("StaticFieldLeak")
        private lateinit var instant: AppContext

        var serviceConnected = false

        @JvmStatic
        @JvmName("get")
        fun get(): AppContext {
            return instant
        }
    }

    private lateinit var actionSound: ActionSound

    private var appService: AppService? = null

    override fun onCreate() {
        super.onCreate()
        instant = this
        Hawk.init(this).build()
        LocalDataDao.INSTANCE
        BleManager.getInstance().init(this)
        BleManager.getInstance()
            .enableLog(true)
            .setReConnectCount(2, 2000)
            .setSplitWriteNum(20)
            .setConnectOverTime(10000).operateTimeout = 10000
        actionSound = ActionSound()
        connectService()

//        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
//            if (!BleManager.getInstance().bluetoothAdapter.isLe2MPhySupported){
//                return
//            }
//            if (!BleManager.getInstance().bluetoothAdapter.isLeCodedPhySupported){
//                return
//            }
//            val parameters = AdvertisingSetParameters.Builder()
//                .setLegacyMode(false)
//                .setInterval(AdvertisingSetParameters.INTERVAL_HIGH)
//                .setTxPowerLevel(AdvertisingSetParameters.TX_POWER_MEDIUM)
//                .setPrimaryPhy(BluetoothDevice.PHY_LE_1M)
//                .setSecondaryPhy(BluetoothDevice.PHY_LE_CODED)
//                .build()
//
//            val data = AdvertiseData.Builder().setIncludeDeviceName(true).build()
//            var currentAdvertisingSet:AdvertisingSet
//
//            val callback: AdvertisingSetCallback = object : AdvertisingSetCallback() {
//                override fun onAdvertisingSetStarted(
//                    advertisingSet: AdvertisingSet,
//                    txPower: Int,
//                    status: Int
//                ) {
//                    Log.i(
//                        LOG_TAG, "onAdvertisingSetStarted(): txPower:" + txPower + " , status: "
//                                + status
//                    )
//                    currentAdvertisingSet = advertisingSet
//                    currentAdvertisingSet.setAdvertisingData(
//                        AdvertiseData.Builder().setIncludeDeviceName(true).setIncludeTxPowerLevel(true)
//                            .build()
//                    )
//                    // Wait for onAdvertisingDataSet callback...
//                    currentAdvertisingSet.setScanResponseData(
//                        AdvertiseData.Builder().addServiceUuid(ParcelUuid(UUID.randomUUID())).build()
//                    )
//                }
//
//                override fun onAdvertisingDataSet(advertisingSet: AdvertisingSet, status: Int) {
//                    Log.i(
//                        LOG_TAG,
//                        "onAdvertisingDataSet() :status:$status"
//                    )
//                }
//
//                override fun onScanResponseDataSet(advertisingSet: AdvertisingSet, status: Int) {
//                    Log.i(
//                        LOG_TAG,
//                        "onScanResponseDataSet(): status:$status"
//                    )
//                }
//
//                override fun onAdvertisingSetStopped(advertisingSet: AdvertisingSet) {
//                    Log.i(LOG_TAG, "onAdvertisingSetStopped():")
//                }
//            }
//            BleManager.getInstance().bluetoothAdapter.bluetoothLeAdvertiser
//                .startAdvertisingSet(parameters, data, null, null, null, callback)
//
//            // When done with the advertising:
////            advertiser.stopAdvertisingSet(callback)
//
//
//        }

    }

    fun alarm(address: String) {
        actionSound.alarm(instant, address)
    }

    fun alarm(probeIndex: Int, address: String) {
        actionSound.alarm(instant, probeIndex, address)
    }

    override fun onTerminate() {
        actionSound.release()
        super.onTerminate()
    }

    fun stopAlarm(address: String) {
        println("======>  stopAlarm $address")
        actionSound.stop(instant, address)
    }

    fun stopAlarm() {
        actionSound.stop(instant)
    }

    fun stopAlarm(probeIndex: Int, address: String) {
        actionSound.stop(instant, probeIndex, address)
    }

    fun connectService() {
        val intent = Intent(this, AppService::class.java)
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
        println("=====>  connectService")
    }

    fun isServiceConnected(): Boolean {
        return appService!=null && serviceConnected
    }

    fun isServiceWorking():Boolean{
        return  appService!=null && serviceConnected && appService?.isWorking()?:false
    }

    fun disConnectService() {
        if (serviceConnected) {
            appService?.stopWorking()
            unbindService(mConnection)
            serviceConnected = false
        }
    }

    fun startCheckConnectWorking(activity: FragmentActivity) {
        appService?.startCheckConnectWorking(activity)
    }

    fun stopBleWorking() {
        appService?.stopWorking()
    }

    private var mConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            serviceConnected = false
            appService = null
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            serviceConnected = true
            val binder = service as AppService.LocalBinder
            appService = binder.service
        }
    }

    fun getTypeFace(): Typeface {
        return Typeface.createFromAsset(assets, "DS-DIGIB-2.ttf")
    }


    override fun getResources(): Resources {
        val resources = super.getResources()
        if (resources != null) {
            val configuration = resources.configuration
            val fontScale = configuration.fontScale
            val densityDpi = configuration.densityDpi
            println("===fontScale=$fontScale  densityDpi=$densityDpi")
            val newFont = if (fontScale > 1F) {
                (fontScale - 1) / 2 + 1
            } else {
                fontScale
            }
            configuration.fontScale = newFont   //0.85:小号  1:标准  1.25:大号  1.4:巨无霸
            if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.N){
                if (resources.displayMetrics.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE) {
                    configuration.densityDpi = DisplayMetrics.DENSITY_DEVICE_STABLE // 恢复显示大小
                }
            }
//            createConfigurationContext(configuration)
//            resources.updateConfiguration(configuration, resources.displayMetrics)
        }
        return resources
    }


}